<template>
  <div id="roles">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="add_users_roles_visible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="role_list" border stripe>
        <!-- 通过for循环，渲染一二三级权限 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bd_bottom', i1 === 0 ? 'bd_top' : '', 'vccenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染以及权限 -->
              <el-col :span="5">
                <el-tag closable @close="del_right_id(scope.row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二三级权限 -->
              <el-col :span="19">
                <!-- 通过 for 循环，嵌套渲染二级权限 -->
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'bd_top', 'vccenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="del_right_id(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="del_right_id(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <!-- 编辑角色区域 -->
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="eidt_dialog_btn(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="del_dialog_visible_btn(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="show_set_right_dialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加用户对话框区域 -->
    <el-dialog
      title="添加用户"
      :visible.sync="add_users_roles_visible"
      width="50%"
      @close="add_dialog_close"
    >
      <!-- 弹出框内容区域 -->
      <el-form label-width="80px" :model="role_form" ref="add_form_ref">
        <!-- 角色名称输入框 -->
        <el-form-item label="角色名称" prop="role_name">
          <el-input v-model="role_form.roleName"></el-input>
        </el-form-item>
        <!-- 角色描述 -->
        <el-form-item label="角色描述" prop="role_desc">
          <el-input v-model="role_form.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="add_users_roles_visible = false">取 消</el-button>
        <el-button type="primary" @click="add_users_roles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色对话框区域 -->
    <el-dialog
      title="修改用户"
      :visible.sync="eidt_users_roles_visible"
      width="50%"
      @close="eidt_dialog_close"
    >
      <!-- 弹出框内容区域 -->
      <el-form label-width="80px" :model="eidt_form" ref="eidt_form_ref" row-key="id">
        <!-- 角色名称输入框 -->
        <el-form-item label="角色名称" prop="role_name">
          <el-input v-model="eidt_form.roleName"></el-input>
        </el-form-item>
        <!-- 角色描述 -->
        <el-form-item label="角色描述" prop="role_desc">
          <el-input v-model="eidt_form.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="eidt_users_roles_visible = false">取 消</el-button>
        <el-button type="primary" @click="eidt_users_info">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框区域 -->
    <el-dialog
      title="提示"
      :visible.sync="set_right_dialog_visible"
      width="50%"
      @close="set_right_dialog_close"
    >
      <el-tree
        :data="rights_list"
        :props="tree_props"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="def_keys"
         ref="tree_ref"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="set_right_dialog_visible = false">取 消</el-button>
        <el-button type="primary" @click="set_right_dialog_btn"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      role_list: [],
      // 隐藏添加用户的弹出框
      add_users_roles_visible: false,
      // 提交表单的角色信息
      role_form: {
        roleName: "",
        roleDesc: "",
      },
      // 隐藏修改角色弹出框
      eidt_users_roles_visible: false,
      // 查询到的用户信息
      eidt_form: {},
      // 控制分配权限对话框的显示与隐藏
      set_right_dialog_visible: false,
      // 获取所有权限信息
      rights_list: [],
      // 树形控件的属性
      tree_props: {
        children: "children",
        label: "authName",
      },
      // 默认选中的id值数组
      def_keys:[],
      // 当前即将分配权限的角色id
      role_id:""
    };
  },
  created() {
    this.get_role_list();
  },
  methods: {
    // 获取所有角色信息
    async get_role_list() {
      let { data: res } = await this.axios.get("roles", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.message.error("获取角色列表失败");
      }
      this.role_list = res.data;
    },
    // 监听添加用户对话框关闭事件
    add_dialog_close() {
      this.$refs.add_form_ref.resetFields();
    },
    // 点击按钮，添加角色
    add_users_roles() {
      this.$refs.add_form_ref.validate(async (valid) => {
        if (!valid) return;
        console.log(valid);
        // 可以发起添加用户的网络请求
        let { data: res } = await this.axios.post("roles", this.role_form);
        if (res.meta.status !== 201) {
          return this.message.error("添加用户失败！");
        }
        this.message.success("添加用户成功！");
        // 隐藏添加用户的对话框
        this.add_users_roles_visible = false;
        this.get_role_list();
      });
    },
    // 点击按钮，修改角色
    async eidt_dialog_btn(id) {
      let { data: res } = await this.axios.get("roles/" + id);
      if (res.meta.status !== 200) {
        return this.message.error("获取用户信息失败");
      }
      this.eidt_form = res.data;
      console.log(this.eidt_form);
      this.eidt_users_roles_visible = true;
    },
    // 监听修改角色对话框关闭事件
    eidt_dialog_close() {
      this.$refs.eidt_form_ref.resetFields();
    },
    // 修改角色信息并提交
    eidt_users_info() {
      this.$refs.eidt_form_ref.validate(async (valid) => {
        if (!valid) return;
        // 发起修改角色信息的请求
        let { data: res } = await this.axios.put(
          "roles/" + this.eidt_form.roleId,
          {
            roleName: this.eidt_form.roleName,
            roleDesc: this.eidt_form.roleDesc,
          }
        );
        if (res.meta.status !== 200) {
          return this.message.error("更改角色信息失败");
        }
        // 关闭对话框
        this.eidt_users_roles_visible = false;
        // 提示更改成功
        this.message.success("更改角色信息成功");
        // 重新获取数据
        this.get_role_list();
      });
    },
    // 点击按钮，删除角色
    async del_dialog_visible_btn(id) {
      let confirm_result = await this.confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // 点击确定，返回confirm
      // 点击取消，返回cancel
      if (confirm_result !== "confirm") {
        return this.message.info("已取消删除");
      }
      let { data: res } = await this.axios.delete("roles/" + id);

      if (res.meta.status !== 200) {
        return this.message.error("删除用户失败");
      }
      this.message.success("删除用户成功");
      this.get_role_list();
    },
    // 根据id删除对应的权限
    async del_right_id(role, right) {
      // 弹窗询问是否删除
      let cofirm_result = await this.confirm(
        "此操作将永远删除此权限，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (cofirm_result !== "confirm") {
        return this.message.info("已取消删除");
      }

      let { data: res } = await this.axios.delete(
        `roles/${role.id}/rights/${right}`
      );
      if (res.meta.status !== 200) {
        return this.message.error("删除权限失败");
      }
      this.message.success("删除权限成功");
      role.children = res.data;
    },
    // 展示分配权限对话框
    async show_set_right_dialog(role) {
      this.role_id = role.id
      let { data: res } = await this.axios.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.message.error("获取权限信息失败");
      }
      // 把获取到的权限数据保存到data中
      this.rights_list = res.data;
      // this.def_keys = res.d
      this.get_leafe_keys(role,this.def_keys)
      
      this.set_right_dialog_visible = true
    },
    // 通过递归的形式，获取当前角色下所有三级节点的id
    get_leafe_keys(node, arr){
      // 如果当前node节点不包含children属性则是三级节点
      if(!node.children){
        return arr.push(node.id);
      }
      node.children.forEach(item => {
        this.get_leafe_keys(item,arr)
      })
    },
    // 监听权限分配对话框关闭，清空 def_key 数组中的值
    set_right_dialog_close(){
      this.def_keys = []
    },
    // 点击确定为角色分配权限
    async set_right_dialog_btn(){
      let keys = [
        ...this.$refs.tree_ref.getCheckedKeys(),
        ...this.$refs.tree_ref.getHalfCheckedKeys()
      ]
      console.log(keys)
      let id_str = keys.join(",")
      let {data: res} = await this.axios.post(`roles/${this.role_id}/rights`,{
        rids: id_str
      })
      if(res.meta.status !== 200){
        return this.message.error("更新权限信息失败")
      }
      this.message.success("更新权限成功")
      this.get_role_list()
      this.set_right_dialog_visible = false
    }
  },
};
</script>
<style lang="less" scoped>
.vccenter {
  display: flex;
  align-items: center;
}
.el-table{
  margin-top: 15px;
}
</style>